const db = require("../model/mysql/db");
const util = require("../common/util");
const moment = require('moment-timezone');
const e = require("express");

async function addPost(req, res) {
    const requiredFields = ['user_id','content'];
    const missing = requiredFields.filter(field => !req.body[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }
    const date = new Date();
    const chinaTime = new Date(date.getTime() + 8 * 60 * 60 * 1000);
    console.log(chinaTime.toISOString()); 
    let params = [
            req.body.user_id,
            req.body.content,
            chinaTime.toISOString()
        ] 
    const sql = "INSERT INTO posts (user_id,content,post_time) VALUES(?,?,?);"
    try {
        let result =await db.query(sql,params);
        util.FormatJSONData(201,"插入成功");
        res.status(201).json(util.FormatJSONData(201,"插入成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}
async function addimg(req, res) { 
    const requiredFields = ['post_id','url'];
    const missing = requiredFields.filter(field => !req.body[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    };
    let params = [
            req.body.post_id,
            req.body.url
        ];
    const sql = "INSERT INTO postimg (post_id,url) VALUES(?,?);"
    try {
        let result =await db.query(sql,params);
        util.FormatJSONData(201,"插入成功");
        res.status(201).json(util.FormatJSONData(201,"插入成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}

async function search(req, res) {
    let uid = parseInt(req.query.user_id);
    let keyword = req.query.content;
    // const sql = `SELECT 
    //     p.post_id,
    //     p.user_id,
    //     us.avatar,
    //     us.nickname,
    //     p.review_count,
    //     p.content,
    //     p.post_time,
    //     p.like_count,
    //     p.dislike_count,
    //     COALESCE(
    //         (SELECT act FROM likepost 
    //         WHERE post_id = p.post_id AND user_id = ? LIMIT 1), 
    //         0
    //     ) AS act,
    //     COALESCE(
    //         (SELECT JSON_ARRAYAGG(url) 
    //         FROM (SELECT DISTINCT url FROM postimg WHERE post_id = p.post_id) AS tmp), 
    //         JSON_ARRAY()
    //     ) AS urls,
    //     IF(COUNT(lp.\`like\`) > 0, 1, 0) AS liked,  -- 保留字用反引号转义
    //     IF(COUNT(lp.dislike) > 0, 1, 0) AS disliked
    //     FROM posts AS p
    //     LEFT JOIN postimg AS i ON p.post_id = i.post_id
    //     LEFT JOIN likepost AS lp 
    //     ON p.post_id = lp.post_id AND lp.user_id = ?
    //     LEFT JOIN users AS us ON p.user_id = us.user_id
    //     WHERE p.content LIKE CONCAT('%', ?, '%')
    //     GROUP BY p.post_id, p.user_id, us.avatar, us.nickname, p.content, 
    //             p.post_time, p.like_count, p.dislike_count
    //     ORDER BY p.post_time DESC;`

    const sql = `SELECT 
            p.post_id,
            p.user_id,
            us.avatar,
            us.nickname,
            p.review_count,
            p.content,
            p.post_time,
            p.like_count,
            p.dislike_count,
            COALESCE(MAX(lp.act), 0) AS act,  -- 处理空值
            COALESCE(JSON_ARRAYAGG(i.url), JSON_ARRAY()) AS urls, -- 处理空图片
            COALESCE(MAX(lp.\`like\`), 0) AS liked,
            COALESCE(MAX(lp.dislike), 0) AS disliked
            FROM posts AS p
            LEFT JOIN postimg AS i ON p.post_id = i.post_id
            LEFT JOIN likepost AS lp 
                ON p.post_id = lp.post_id 
                AND lp.user_id = ?  -- 关键修改点：条件放在JOIN里
            LEFT JOIN users AS us ON p.user_id = us.user_id
                WHERE p.content LIKE CONCAT('%', ?, '%')
            GROUP BY p.post_id    -- 简化分组
            ORDER BY p.post_time DESC;`
    
    let params = [uid,keyword];
    util.log(params);
    try {
        let result =await db.query(sql,params);
        util.log(util.FormatJSONData(201,"查询成功",result));
        for (let i = 0; i < result.length; i++) {
            result[i].post_time = moment(result[i].post_time).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
            if (!result[i].liked) result[i].liked = false;
            else result[i].liked = true;

            if (!result[i].disliked) result[i].disliked = false;
            else result[i].disliked = true;

            if (!result[i].act) result[i].act = 0;

            if (!result[i].urls[0]) result[i].urls = [];
            console.log(result[i].urls);
        }
        res.status(201).json(util.FormatJSONData(201,"查询成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}

async function findall(req, res) {
    let uid = req.params.user_id;
    const sql = `SELECT 
    p.post_id,
    p.user_id,
    us.avatar,
    us.nickname,
    p.review_count,
    p.content,
    p.post_time,
    p.like_count,
    p.dislike_count,
    COALESCE(MAX(lp.act), 0) AS act,  -- 处理空值
    COALESCE(JSON_ARRAYAGG(i.url), JSON_ARRAY()) AS urls, -- 处理空图片
    COALESCE(MAX(lp.\`like\`), 0) AS liked,
    COALESCE(MAX(lp.dislike), 0) AS disliked
    FROM posts AS p
    LEFT JOIN postimg AS i ON p.post_id = i.post_id
    LEFT JOIN likepost AS lp 
        ON p.post_id = lp.post_id 
        AND lp.user_id = ?  -- 关键修改点：条件放在JOIN里
    LEFT JOIN users AS us ON p.user_id = us.user_id
    GROUP BY p.post_id    -- 简化分组
    ORDER BY p.post_time DESC;
`
    console.log(sql);
    util.log(uid);
    try {
        let result =await db.query(sql,[uid]);
        util.FormatJSONData(201,"查询成功");
        // res.forEach((item,index) => {
        //     console.log(item);
        // });
        console.log(result);
        for (let i = 0; i < result.length; i++) {
            result[i].post_time = moment(result[i].post_time).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
            if (!result[i].liked) result[i].liked = false;
            else result[i].liked = true;

            if (!result[i].disliked) result[i].disliked = false;
            else result[i].disliked = true;

            if (!result[i].act) result[i].act = 0;

            if (!result[i].urls[0]) result[i].urls = [];
            console.log(result[i].urls);
        }
        res.status(201).json(util.FormatJSONData(201,"查询成功",result));
        
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}

async function findone(req, res) {
    let post_id = parseInt(req.query.pid);
    let user_id = parseInt(req.query.uid);
    util.log(post_id);
    util.log(user_id);
    const sql = `SELECT 
    p.post_id,
    p.user_id,
    us.avatar,
    us.nickname,
    p.review_count,
    p.content,
    p.post_time,
    p.like_count,
    p.dislike_count,
    COALESCE(MAX(lp.act), 0) AS act,
    COALESCE(JSON_ARRAYAGG(i.url), JSON_ARRAY()) AS urls,
    COALESCE(MAX(lp.\`like\`), 0) AS liked,
    COALESCE(MAX(lp.dislike), 0) AS disliked
    FROM posts AS p
    LEFT JOIN postimg AS i ON p.post_id = i.post_id
    LEFT JOIN likepost AS lp 
        ON p.post_id = lp.post_id 
        AND lp.user_id = ?  -- 正确过滤当前用户的点赞行为
    LEFT JOIN users AS us ON p.user_id = us.user_id
    WHERE p.post_id = ?
    GROUP BY 
        p.post_id, 
        p.user_id, 
        us.avatar, 
        us.nickname,
        p.review_count,
        p.content,
        p.post_time,
        p.like_count,
        p.dislike_count
    ORDER BY p.post_time DESC;`
    let params = [user_id,post_id];
    util.log(params);
    try {
        let result =await db.query(sql,[user_id,post_id]);

        result[0].post_time = moment(result[0].post_time).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
        if (!result[0].liked) result[0].liked = false;
        else result[0].liked = true;

        if (!result[0].disliked) result[0].disliked = false;
        else result[0].disliked = true;

        if (!result[0].act) result[0].act = 0;

        if (!result[0].urls[0]) result[0].urls = [];
        console.log(result[0].urls);
        util.log(result[0].nickname);
        // util.log(util.FormatJSONData(201,"查询成功",result));
        res.status(201).json(util.FormatJSONData(201,"查询成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}

async function like(req,res){
    util.log("*********fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff************")
    util.log(req.body);
    let act = req.body.act;
    let like = req.body.like;
    let dislike = req.body.dislike;
    let cancel = req.body.cancel;
    if (like === 1) {  
        let sql = `UPDATE posts SET like_count = like_count + 1 WHERE post_id = ?;`
        try {
            let result =await db.query(sql,[req.body.post_id]);
        } catch{
            util.err(500,"错误！！！");
            res.status(500).json(util.FormatJSONData(500,"服务器错误"));
        }
    } else if (cancel === true) {
        let sql = `UPDATE posts SET like_count = like_count - 1 WHERE post_id = ?;`
        try {
            let result =await db.query(sql,[req.body.post_id]);
            util.log("取消点赞成功");
        } catch{
            util.err(500,"错误！！！");
        }
    } 
    
    if (act !== 0){ 
        util.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        let sql = `UPDATE likepost SET \`like\` = ?, dislike = ? WHERE post_id = ? AND user_id = ?;`
        try {
            let result =await db.query(sql,[req.body.like, req.body.dislike, req.body.post_id, req.body.user_id]);
            util.FormatJSONData(201,"点赞成功");
            util.log(req.body.dislike);
            res.status(201).json(util.FormatJSONData(201,"点赞成功",result));
        } catch{
            util.err(500,"错误！！！");
            res.status(500).json(util.FormatJSONData(500,"服务器错误"));
        }
    } else if (act === 0) {
        let params = [
            req.body.post_id,
            req.body.user_id,
            req.body.like,
            req.body.dislike,
            1
        ]
        let sql = `INSERT INTO likepost (post_id,user_id,\`like\`,dislike,act) VALUES(?,?,?,?,?);`
        console.log(params);
        try {
            let result = await db.query(sql,params);
            res.status(201).json(util.FormatJSONData(201,"操作成功",result));
        } catch{
            util.err(500,"错误！！！");
            res.status(500).json(util.FormatJSONData(500,"服务器错误"));
        }
    }
}

module.exports = {
    addPost,
    addimg,
    findall,
    findone,
    like,
    search
}